package com.model;

/**
 * Created by lwx on 2016/12/3.
 */
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Stack;

public class DB {
    private static DB DB_INSTANCE = null;
    private static int MAX = 40;
    private static Stack<Connection> CON_POOL = new Stack<Connection>();
    // 数据库配置
    private static String name = "com.mysql.jdbc.Driver";
    private static String url = "jdbc:mysql://localhost/BBVideo";
    private static final String user = "root";
    private static final String password = "123456";
    // 同步对象
    private final static byte[] lock = new byte[0];

    private DB() throws ClassNotFoundException {
        Class.forName(name);

    }

    // 返回单一实例
    public static DB getInstance() throws ClassNotFoundException {
        if (DB_INSTANCE == null) {
            DB_INSTANCE = new DB();
        }
        return DB_INSTANCE;
    }

    // 获取连接
    public static Connection getConnection() throws SQLException {
        synchronized (lock) {
            if (CON_POOL.isEmpty()) {
                return DriverManager.getConnection(url,user,password );
            }
            return CON_POOL.pop();
        }
    }

    // 释放连接
    public static void release(Connection con) throws SQLException {
        synchronized (lock) {
            if (con == null || con.isClosed()) {
                return;
            } else if (CON_POOL.size() < MAX + 1) {
                CON_POOL.push(con);
            } else {
                con.close();
            }
        }
    }
}
